package org.smart4j.framework.common.aop.proxy.dynamic;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 动态代理（基于CGLib）
 * CGLib：在运行期间动态生成字节码的工具，动态生成代理类
 * 缺陷：创建代理的速度较慢（但创建代理后的运行速度却非常快，与JDK相反），
 * 如果在运行时候不断用CGLib去创建代理，系统性能会打折扣，因此，建议在系统初始化时用CGLib去创建代理
 *
 * @author YooLin1c
 * @version 1.0.0
 * @since 2018-01-31 16:54
 */
public class CGLibDynamicProxy implements MethodInterceptor {

    private CGLibDynamicProxy() {
    }

    @SuppressWarnings("unckecked")
    public <T> T getProxy(Class<?> clazz) {
        return (T) Enhancer.create(clazz, this);
    }

    @Override
    public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        before();
        Object result = methodProxy.invokeSuper(target, args);
        after();
        return result;
    }

    private void before() {
        System.out.println("before");
    }

    private void after() {
        System.out.println("after");
    }

    public static CGLibDynamicProxy getInstance() {
        return CGLibProxyHolder.INSTANCE;
    }

    private static class CGLibProxyHolder {
        private static final CGLibDynamicProxy INSTANCE = new CGLibDynamicProxy();
    }
}
